<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--<%@ include file="../include/admincontent.jsp" %>--%>
<link rel="stylesheet" href="../resources/js/plugins/layui/css/layui.css"/>
<link rel="stylesheet" href="../resources/css/knowlegPoints.css"/>
<link rel="stylesheet" href="../resources/css/index.css"/>
<style>
    .layui-table-cell {
        overflow: visible !important;
    }
    .layui-table-box {
        overflow: visible;
    }
    .layui-table-body {
        overflow: visible;
    }
    td .layui-form-select{
        margin-top: -10px;
        margin-left: -15px;
        margin-right: -15px;
    }
</style>
<div class="add-test-paper">
    <div id="location">当前位置：笔试管理 > 试卷管理 > 添加试卷</div>
    <div id="content">
        <div class="btnbar">
            <button class="save" id="btn_addPaper_save">
                <em class="ico16 save_traft_16"></em>
                <span class="menu_span" title="保存">保存</span>
            </button>
            <button class="back" onclick="self.location=document.referrer;">
                <em class="ico16 cancle_publish_16"></em>
                <span class="menu_span" title="返回">返回</span>
            </button>
        </div>
        <div class="table-cont">
            <input name=paperStatess value="${paperState}" style="display: none">
            <input name=addNamess  value="${addName}" style="display: none">
            <input name=addTimess value="${addTime}" style="display: none">
            <form id="paperForm">
                <table class="treeTable inputform" cellpadding="0" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <td colspan="2" class="table-title">试卷信息</td>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td width="90">试卷用途：</td>
                            <td><select id="paperPurpose" name="paperPurpose" datatype="*" nullmsg="试卷用途不能为空！">
                                <c:choose>
                                    <c:when test="${paperPurpose==1}">
                                        <option value="0">练习用卷</option>
                                        <option value="1" selected="selected">考试用卷</option>
                                    </c:when>
                                    <c:otherwise>
                                        <option value="0" selected="selected">练习用卷</option>
                                        <option value="1">考试用卷</option>
                                    </c:otherwise>
                                </c:choose>
                            </select></td>
                        </tr>
                        <tr>
                            <td>试卷类型：</td>
                            <td><select id="paperType" name="paperType" datatype="*" nullmsg="试卷类型不能为空！">
                                <c:choose>
                                    <c:when test="${paperType==0}">
                                        <option value="0" selected="selected">固定试卷</option>
                                        <option value="1">随机试卷</option>
                                    </c:when>
                                    <c:otherwise>
                                        <option value="0">固定试卷</option>
                                        <option value="1" selected="selected">随机试卷</option>
                                    </c:otherwise>
                                </c:choose>
                            </select></td>
                        </tr>
                        <tr>
                            <td>所属岗位：</td>
                            <td><select id="position" name="position" datatype="*" nullmsg="所属岗位不能为空！">
                                <option value="">请选择岗位</option>
                                <c:forEach var="baseJobs" items="${jobs}" varStatus="item" >
                                    <c:choose>
                                        <c:when test="${baseJobs!=null}">
                                            <c:choose>
                                                <c:when test="${position==baseJobs.name}">
                                                    <option value="${baseJobs.name}" selected="selected">${baseJobs.name}</option>
                                                </c:when>
                                                <c:otherwise>
                                                    <option value="${baseJobs.name}">${baseJobs.name}</option>
                                                </c:otherwise>
                                            </c:choose>
                                        </c:when>
                                    </c:choose>
                                </c:forEach>
                            </select></td>
                        </tr>
                        <tr>
                            <td>试卷名称：</td>
                            <td><input type="text" name="paperName" style="height:30px;" datatype="*" value="${paperName}" nullmsg="试卷名称不能为空！" class="test-name-input"></td>
                        </tr>
                        <tr>
                            <td>试卷说明：</td>
                            <td style="padding:10px 5px;">
                                <div class="htmleditor">
                                    <textarea id="paperExplain" name="paperExplain" value="${paperExplain}" datatype="*" nullmsg="题目内容不能为空！" style="width:100%;height:260px;"></textarea>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>试卷总分：</td>
                            <td><input type="text" name="totalScore" style="height:30px;" value="${totalScore}" datatype="zzzs" nullmsg="试卷总分不能为空！"></td>
                        </tr>
                    </tbody>
                </table>
            </form>

                <div style="width: 100%;background-color: #EEF1F8;line-height: 40px;margin-top: 10px;">
                    <div>
                        <span style="font-size: 12px; color: #666;font-weight: bold">  组 卷 规 则</span>
                    </div>
                    <div>
                    <span style="font-size: 12px; color: #666;">
                        (建议按照以下顺序添加/修改试卷：单项选择题→不定项选择→填空题→判断正误题→简答题→综合题）</span>
                        <button id="btn_del_all" type="button" style="float: right;margin-right: 20px;margin-top: 8px;width: 80px;background-color: orangered"
                                class="layui-btn layui-btn-xs"> 批量删除 </button>
                        <button id="btn_add_line" type="button" style="float: right;margin-right: 10px;margin-top: 8px;width: 80px;background-color: #2b8af4"
                                class="layui-btn layui-btn-xs"> 增加一行 </button>
                        <input type="text" id="getAllCnt" name="getAllCnt" style="float: right;height:25px;margin-right: 20px;margin-top: 8px;width: 80px;" class="test-name-input">
                        <span style="float: right;font-size: 12px; color: #666;font-weight: bold" >总分：</span>
                    </div>
                </div>

                <table id="plistTable" lay-filter="plistTable" ></table>

        </div>
    </div>
</div>

<div id="select-konwleg" class="other-page">
    <p class="help">红色显示的部分表示该知识点题库不满足抽题要求</p>
    <div class="btnbar">
        <button class="save" id="btn_addKnow_save">
            <em class="ico16 save_traft_16"></em>
            <span class="menu_span" title="保存">保存</span>
        </button>
    </div>
    <table id="knowlegTable" lay-filter="knowlegTable" ></table>
</div>

<script type="text/javascript" src="../resources/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../resources/js/plugins/layui/layui.js"></script>
<script type="text/javascript" src="../resources/js/actions.js"></script>
<script src="../resources/js/fadeInout.js" type="text/javascript"></script>

<script type="text/javascript" language="javascript">
    $(function () {
        var chooseID = null;
        var plistTable = null;
        var chooseTopicType = null;
        var pPosition = "";

        layui.use(['table', 'form'], function () {
            plistTable = layui.table;
            var form = layui.form;

            // 监听修改update到表格中
            form.on('select(rangeSelect)', function (data) {
                var elem = $(data.elem);
                var trElem = elem.parents('tr');
                var tableData = plistTable.cache['plistTable'];
                // 更新到表格的缓存数据中，才能在获得选中行等等其他的方法中得到更新之后的值
                tableData[trElem.data('index')][elem.attr('name')] = data.value;

            });


            plistTable.render({
                elem: '#plistTable',
                url: '/PaperManager/getPaperContentList?id=${id}', //数据接口
               // page: true,
                title:'组卷规则',
                height: 'full',
                cellMinWidth: 40, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                cols: [[
                        { field: 'paperChapter', title: '试卷章节',edit:true, width: 80},
                        { field: 'topicType', title: '题型', width: 150, templet: function(d){
                            return '<select name="topicType"  lay-filter="rangeSelect" lay-verify="required" data-value="'+d.topicType+'">\n' +
                                    '<option value="单项选择题">单项选择题</option>\n' +
                                    '<option value="不定项选择题">不定项选择题</option>\n' +
                                    '<option value="填空题">填空题</option>\n' +
                                    '<option value="判断正误题">判断正误题</option>\n' +
                                    '<option value="简答题">简答题</option>\n' +
                                    '<option value="综合题">综合题</option>\n</select>';
                        } },
                        { field: 'rangeQuestion', title: '抽题范围',event:'btn_choose'},
                        { field: 'totalTopics', title: '题目总数', width: 80},
                        { field: 'scoreQuestion', title: '每题分值' , width: 80,edit:true},
                        { field: 'sort', title: '排序', width: 80,edit:true,hide:true,templet: function(d){
                            return '<span>1</span>'; }},
                        { field: 'add', title: '', width: 100,event:'btn_add',templet: function(d){
                                return '<button type="button" class="layui-btn layui-btn-xs" lay-filter="btn_add" >增加</button>';
                        }},
                        { field: 'del', title: '', width: 100,event:'btn_del',templet: function(d){
                                return '<button type="button" class="layui-btn layui-btn-xs"  lay-filter="btn_del" >删除</button>';
                        } },
                    ],
                ],
                done: function (res, curr, count) {
                    var aCnt = 0;
                    for(var i in res.data){
                        if(res.data[i].scoreQuestion !== "")
                            aCnt += res.data[i].totalTopics * res.data[i].scoreQuestion;
                    }
                    $("input[name='getAllCnt']").val(aCnt);

                    var tableElem = this.elem.next('.layui-table-view');
                    count || tableElem.find('.layui-table-header').css('overflow', 'auto');
                    layui.each(tableElem.find('select'), function (index, item) {
                        var elem = $(item);
                        elem.val(elem.data('value')).parents('div.layui-table-cell').css('overflow', 'visible');
                    });
                    form.render();
                },
            });


            plistTable.on('edit(plistTable)', function(obj){
                var aCnt = 0;
                var getData = plistTable.cache["plistTable"];
                for(var i in getData){
                    if(getData[i].scoreQuestion !== "")
                        aCnt += getData[i].totalTopics * getData[i].scoreQuestion;
                }
                $("input[name='getAllCnt']").val(aCnt);

            });

            plistTable.on('tool(plistTable)', function (obj) {
                if (obj.event === 'btn_add') {
                    var ids = obj.data.idnum + 1;
                    addTableLine(ids);
                }else if (obj.event === 'btn_del') {
                    var getData = plistTable.cache["plistTable"];
                    var ids = obj.data.idnum;

                    if(ids === (getData.length-1)){
                        listableReload(plistTable,getData.slice(0,getData.length-1));
                    }else {
                        var arr = new Array();
                        for(var x=0;x<ids;x++)
                            arr.push(getData[x]);
                        for(var y=ids;y<(getData.length-1);y++){
                            getData[y+1].idnum = y;
                            arr.push(getData[y+1]);
                        }

                        listableReload(plistTable,arr);
                    }
                }else if (obj.event === 'btn_choose') {
                    pPosition = $("#position").val();

                    if(pPosition==="")
                        layer.msg('请先选择所属岗位！',{icon:2});
                    else {
                        chooseID = obj.data.idnum;
                        chooseTopicType = obj.data.topicType;
                        if(chooseTopicType == "")
                            layer.msg('题目类型！',{icon:2});
                        else{
                            layer.open({
                                type: 1,
                                title: '选择知识点',
                                content: $('#select-konwleg'),
                                offset: '30px',
                                area: ['700px', '600px']
                            })
                            renderTable();
                        }
                    }
                }
            });
        });

        function addTableLine(ids) {
            var getData = plistTable.cache["plistTable"];
            var newData = {
                 "idnum": ids
                , "id": ""
                , "paperChapter": ""
                , "topicType": ""
                , "rangeQuestion": ""
                , "totalTopics": ""
                , "scoreQuestion": ""
            }

            if (ids === getData.length) {
                getData.push(newData);
                listableReload(plistTable, getData);
            } else {
                var arr = new Array();
                for (var x = 0; x < ids; x++)
                    arr.push(getData[x]);
                arr.push(newData);
                for (var y = (ids + 1); y < (getData.length + 1); y++) {
                    getData[y - 1].idnum = y;
                    arr.push(getData[y - 1]);
                }

                listableReload(plistTable, arr);
            }
        }


        function listableReload( p,arr) {
            p.reload('plistTable', {
                url: ""
                , data: arr
            });//data是默认值
        }

        function renderTable() {
            layui.use('table', function () {
                var table = layui.table;

                table.render({
                    elem: '#knowlegTable',
                    url: '/PaperManager/getKnowlegeList', //数据接口
                    page: true,
                    cols: [[
                        { type:'checkbox', fixed:'left', width: 50 },
                        { field: 'name', title: '知识点', },
                        { field: 'major', title: '所属专业', width: 200 },
                        { field: 'type', title: '题目类型', width: 120 },
                        { field: 'allnum', title: '题库数量', width: 80 ,templet: function(d){
                                if((d.allnum < d.num) || (d.num == 0) || (d.allnum == 0))
                                    return '<span style="color: red"> '+d.allnum+' </span>';
                                else
                                    return '<span> '+d.allnum+' </span>';
                            }},
                        { field: 'num', title: '抽题数量', width: 80 ,templet: function(d){
                                if((d.allnum < d.num) || (d.num == 0) || (d.allnum == 0))
                                    return '<span style="color: red"> '+d.num+' </span>';
                                else
                                    return '<span> '+d.num+' </span>';
                            }},
                    ],],
                    where:{
                        key:{
                            tType:chooseTopicType,
                            tPosition:pPosition,
                        }
                    },
                    done: function(res, curr, count){
                        chooseName = null;
                        allnum = null;
                        cnum = null;
                        ckid = null;
                    }
                });
            })
        }
        //增加一行
        $("#btn_add_line").on('click', (e) => {
            addTableLine(0);
        });
        //全部删除
        $("#btn_del_all").on('click', (e) => {
            listableReload(plistTable, new Array());
        });
        //增加试卷
        $("#btn_addPaper_save").on('click', (e) => {

            var idTemp = GetQueryString('id');
            var urlTemp;
            if(idTemp != null)
                urlTemp =  '/PaperManager/editPaper';
            else
                urlTemp =  '/PaperManager/addPaper';

            var getData = plistTable.cache["plistTable"];
            var flags = true;
            for(var i in getData) {
                allCnt += parseInt(getData[i].totalTopics);
                if ((getData[i].paperChapter === "") || (getData[i].topicType === "") || (getData[i].rangeQuestion === "")
                    || (getData[i].scoreQuestion === "") || (getData[i].totalTopics === "") || (getData[i].sort === "")) {
                    flags = false;
                    break;
                }
            }

            var paperStateTemp = $("input[name='paperStatess']").val();
            var addNameTemp = $("input[name='addNamess']").val();
            var addTimeTemp = $("input[name='addTimess']").val();

            var pName = $("input[name='paperName']").val();
            var pPurpose = $("#paperPurpose").val();
            var pType = $("#paperType").val();
            pPosition = $("#position").val();
            var pExplain = $("#paperExplain").val();
            var pScore = $("input[name='totalScore']").val();
            var allCnt = $("input[name='getAllCnt']").val();

            if(pPosition==="")
                layer.msg('请选择所属岗位！',{icon:2});
            else {
                if(!flags)
                    layer.msg('组卷规则不能为空！',{icon:2});
                else {
                    if(Number(allCnt) !== Number(pScore))
                        layer.msg('当前试卷不符合“试卷总分"要求！',{icon:2});
                    else{
                        if(pName === "")
                            layer.msg('试卷名称不能为空！',{icon:2});
                        else {
                            var params2 = JSON.stringify(plistTable.cache["plistTable"]);
                            var params;

                            if(idTemp != null)
                                params = {id:idTemp,paperState:paperStateTemp,addName:addNameTemp,addTime:addTimeTemp,
                                    paperName:pName,paperPurpose:pPurpose,paperType:pType,position:pPosition,
                                    paperExplain:pExplain,totalScore:pScore,listJson:params2};
                            else
                                params = { paperName:pName,paperPurpose:pPurpose,paperType:pType,position:pPosition,
                                    paperExplain:pExplain,totalScore:pScore,listJson:params2};

                            $.ajax({
                                url:urlTemp,
                                data:params,
                                dataType:'JSON',
                                type:'POST',
                                success:function (data) {
                                    if (data.state)
                                        layer.msg(data.Message, {icon: 1, time: 2000});
                                    else
                                        layer.msg(data.Message, {icon: 2, time: 2000});
                                }
                            });
                        }
                    }
                }
            }
        });
        //增加抽查范围
        $("#btn_addKnow_save").on('click', (e) => {
            var flag = getTableChecks();

            if(flag){
                if((allnum < cnum)||(cnum < 1)){
                    layer.msg("该知识点题库不满足抽题要求",{icon:2});
                }else{
                    layer.closeAll();
                    var getData = plistTable.cache["plistTable"];
                    getData[chooseID].rangeQuestion = chooseName;
                    getData[chooseID].totalTopics = cnum;
                    getData[chooseID].kid = ckid;
                    listableReload(plistTable,getData);
                }
            }
        });

        var chooseName = null;
        var allnum = null;
        var cnum = null;
        var ckid = null;
        function getTableChecks(){
            var selectData = layui.table.checkStatus('knowlegTable').data;

            if(selectData.length === 1){
                chooseName = selectData[0].name;
                allnum = selectData[0].allnum;
                cnum = selectData[0].num;
                ckid = selectData[0].kid;
                return true
            }else if(selectData.length < 1){
                layer.msg("请选择一个知识点",{icon:2});
                return false;
            }else{
                layer.msg("一次只能选择一个知识点",{icon:2});
                return false;
            }
        }

     })

</script>